<template>
<div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <!-- gutter为行元素之间设置间隙 -->
        <el-row gutter=20>
            <el-col :span="7">
                <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @clear="getUserList">
           <template #append>
           <el-button icon="el-icon-search" @click="getUserList"></el-button>
           </template>
        </el-input>
        </el-col>
        <el-col :span="4"><el-button type="primary" @click="adddialogVisible=true">添加用户</el-button></el-col>
        </el-row>
        <!-- 添加表格 -->
        <el-table :data="userlist" border stripe="">
          <el-table-column type="index"></el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email" width="170px"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name"></el-table-column>
          <el-table-column label="状态">
          <template v-slot="scope">
            <!-- slot-scope拿到mgstate的值 -->
            <el-switch v-model="scope.row.mg_state" @change="userstatechange(scope.row)">
            </el-switch>
          </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template v-slot="scope">
             <el-button v-model="scope.row.mg_state" type="primary" icon="el-icon-edit" size="mini" @click="showeditdialog(scope.row.id)"></el-button>
             <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
             <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
               <el-button type="warning" icon="el-icon-setting" size="mini" @click="setrole(scope.row)">
               </el-button>
             </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 添加分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!-- queryInfo.pagesize当前每页展示多少条 -->
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" v-model="adddialogVisible" width="50%" @close="adddialogreset">
      <el-form :model="addForm" :rules="addformrules" ref="addruleFormref" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <!-- prop用来校验规则，与规则里的名称对应 -->
          <el-input v-model="addForm.username">
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password">
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email">
          </el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile">
          </el-input>
        </el-form-item>
  </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adddialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑用户对话框 -->
     <el-dialog title="修改用户" v-model="editdialogVisible" width="50%" @close="editdialogreset">
      <el-form :model="editForm" :rules="editformrules" ref="editruleFormref" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email">
          </el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile">
          </el-input>
        </el-form-item>
  </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色"  v-model="setroledialogVisible" width="50%" @close="setroledialogreset">
      <p>当前的用户：{{setroleuserinfo.username}}</p>
      <p>当前的角色：{{setroleuserinfo.role_name}}</p>
      <el-select v-model="selectroleid" placeholder="请选择">
    <el-option
      v-for="item in roleslist"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setroledialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setroleUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
</div>
</template>

<script>
export default {
  data() {
    // 验证邮箱规则
    var checkEmail = (rule, value, callback) => {
    // 邮箱正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱格式'))
    }
    var checkMoile = (rule, value, callback) => {
    // 邮箱正则表达式
      const regMoile = /^(?:\+?86)?1(?:3\d{3}|5[^4\D]\d{2}|8\d{3}|7(?:[35678]\d{2}|4(?:0\d|1[0-2]|9\d))|9[189]\d{2}|66\d{2})\d{6}$/
      if (regMoile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机格式'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      adddialogVisible: false,
      // 控制修改对话框的显示与关闭
      editdialogVisible: false,
      setroledialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 需要编辑时查询到的用户信息
      editForm: '',
      // 添加用户时的表单验证规则
      addformrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMoile, trigger: 'blur' }
        ]
      },
      // 修改用户时的表单验证规则
      editformrules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMoile, trigger: 'blur' }
        ]
      },
      // 当前需要分配角色的用户信息
      setroleuserinfo: '',
      // 角色信息
      roleslist: [],
      // 选中的分配 角色id
      selectroleid: ''
    }
  },
  // 生命函数，发起请求
  created() {
    this.getUserList()
  },
  methods: {
    // 从数据库获取用户数据
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 监听pagesize改变事件
    handleSizeChange(newsize) {
      // console.log(newsize)
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    // 监听页码值的改变
    handleCurrentChange(newpage) {
      // console.log(newpage)
      this.queryInfo.pagenum = newpage
      this.getUserList()
    },
    // 监听用户状态值的改变
    async userstatechange(userinfo) {
      console.log(userinfo)
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 关闭增加用户对话框时对；里面进行清空重置  用到ref  监听对话框的close事件
    adddialogreset() {
      this.$refs.addruleFormref.resetFields()
    },
    // 关闭编辑对话框时，对里面的内容通过ref进行重置
    editdialogreset() {
      this.$refs.editruleFormref.resetFields()
    },
    // 点击确定按钮，对新增内容进行预验证
    addUser() {
      this.$refs.addruleFormref.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // 可以发起用户新增的网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) this.$message.error('增加用户失败')
        this.$message.success('增加用户成功')
        // 隐藏用户状态栏
        this.adddialogVisible = false
        // 重新获取用户列表
        this.getUserList()
      })
    },
    // 点击编辑按钮，根据id请求请求编辑对话框
    async showeditdialog(id) {
      console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('请求失败')
      this.editForm = res.data
      console.log(this.editForm)
      this.editdialogVisible = true
    },
    // 对修改对话框里的数据进行修改验证上传
    editUser() {
      // 对修改后的数据进行预校验，
      this.$refs.editruleFormref.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // 可以发起用户新增的网络请求
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        // console.log(res)
        if (res.meta.status !== 200) { return this.$message.error('修改用户失败') }
        // 隐藏用户状态栏
        this.editdialogVisible = false
        // 重新获取用户列表
        this.getUserList()
        this.$message.success('修改用户成功')
      })
    },
    // 确认用户是否需要删除用户的弹框
    async removeUserById(id) {
      const confirmresult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 确定返回值为confirm
      // 取消返回值为cancel
      // console.log(confirmresult)
      if (confirmresult !== 'confirm') return this.$message.info('已取消删除')
      // 删除用户信息
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.getUserList()
      this.$message.success('删除用户成功')
    },
    // 显示分配角色对话框
    async setrole(role) {
      // 得到当前需要分配角色的用户信息
      this.setroleuserinfo = role
      // 获取所有角色列表值
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleslist = res.data
      // console.log(this.roleslist)
      this.setroledialogVisible = true
    },
    // 点击按钮，提交分配后的角色名
    async setroleUser() {
      if (!this.selectroleid) return this.$message.info('请分配角色')
      const { data: res } = await this.$http.put(`users/${this.setroleuserinfo.id}/role`, { rid: this.selectroleid })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('分配角色成功')
      this.getUserList()
      this.setroledialogVisible = false
    },
    // 关闭分配角色对话框时，重置框内内容
    setroledialogreset() {
      this.selectroleid = ''
      this.setroleuserinfo = ''
    }
  }
}
</script>
<style lang="less" scoped>
</style>
